<?php

declare(strict_types=1);

namespace So\App\Controller\Backend;

use Hyperf\HttpServer\Annotation\PostMapping;
use So\Annotation\Auth;
use Hyperf\HttpServer\Annotation\GetMapping;
use So\Annotation\Validation;
use So\Controller\Backend;
use So\Annotation\Controller;
use So\Library\Auth as AuthLib;
use Hyperf\Di\Annotation\Inject;
use So\Library\Tree;
use So\Annotation\AdminLog;
use So\Library\Random;
use Hyperf\DbConnection\Db;

/**
 * @Controller(prefix="index")
 * @Auth(nologin={"index/login"},nocheck={"index/auth","index/logout"})
 * @AdminLog({"index/auth","index/logout"})
 */
class IndexController extends Backend
{
    /**
     * Auth类
     * @Inject
     * @var AuthLib
     */
    protected $auth;

    /**
     * 管理员登录
     * @PostMapping("login")
     * @Validation
     */
    public function login($data)
    {
        $login = $this->auth->login($data['username'], $data['password']);
        if ($login === false) {
            return $this->error($this->auth->getError());
        }
        return $this->success('登录成功', $login);
    }

    /**
     * 获取管理员权限
     * @GetMapping("auth")
     */
    public function auth()
    {
        $rules = $this->auth->getRuleList($this->auth->jwt(), false, false);
        Tree::instance()->init($rules, 'pid');
        $list = Tree::instance()->getVueMenuList(0, config("default_menu.id"));
        $permission = [];
        foreach ($rules as $rule) {
            if ($rule['type'] == 'button') {
                $permission[] = str_replace('/', '.', ltrim($rule['path'], '/'));
            }
        }
        $list['permission'] = $permission;
        return $this->success('', $list);
    }

    /**
     * 修改资料
     * @PostMapping("profile")
     */
    public function profile()
    {
        $email = input('email/s');
        $password = input('password/s');
        if (!$email) {
            return $this->error('邮箱不能为空');
        }
        $data = ['email' => $email];
        if ($password) {
            $data['salt'] = Random::alnum();
            $data['password'] = md5(md5($password) . $data['salt']);
        }
        Db::table("admin")->where("id", '=', $this->auth->id)->update($data);
        return $this->success('修改成功');
    }

    /**
     * 退出登陆
     * @GetMapping("logout")
     */
    public function logout()
    {
        $this->auth->logout();
        return $this->success("退出登陆成功");
    }

}